import React, { memo, useEffect, useRef } from 'react'
import PropTypes from 'prop-types'
import { IndictorWrapper } from './style'

const Indicator = memo(function Indicator(props) {
  const { children, selectIndex = 0 } = props
  const contentRef = useRef()
  useEffect(() => {
    // 1.获取selectIndex对应的item
    const selectItemEl = contentRef.current.children[selectIndex]
    const itemElOffsetLeft = selectItemEl.offsetLeft
    const itemWidth = selectItemEl.clientWidth

    // 2.content的宽度
    const contentWidth = contentRef.current.clientWidth
    const contentScroll = contentRef.current.scrollWidth

    // 3.获取selectIndex滚动的距离
    let distance = itemElOffsetLeft + itemWidth * 0.5 - contentWidth * 0.5

    // 4.左边的特殊情况处理
    if (distance < 0) distance = 0
    const totalDistance = contentScroll - contentWidth
    // 5.右边的特殊情况处理
    if (distance > totalDistance) distance = totalDistance

    // 6.改变位置
    contentRef.current.style.transform = `translate(${-distance}px)`
  }, [selectIndex])

  return (
    <IndictorWrapper>
      <div className="i-content" ref={contentRef}>
        {children}
      </div>
    </IndictorWrapper>
  )
})

Indicator.propTypes = {
  selectIndex: PropTypes.number,
}

export default Indicator
